/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
Airdroid.Uploader = function (config) {
    var me = this;
    return this._defaultFpath = "/sdcard/",
        this._uploadFilePath = "/sdcard/",
        this._avail = null,
        this._allowSupport = !0,
        this.UPLOADTYPE = {
            XHR: "xhr",
            FLASH: "flash"
        },
        this.UPLOADSERVERTYPE = {
            PHONE: "1",
            SERVER: "2"
        },
        this._uploadType = this.UPLOADTYPE.XHR,
        this._uploadServer = this.UPLOADSERVERTYPE.PHONE,
        me._commonLang = Airdroid.Util.getLang("Common"),
        me._uploadLang = Airdroid.Util.getLang("Upload"),
        me.init(config)
},
    Airdroid.Uploader.prototype = {
        isXHR: function () {
            var me = this;
            return me._uploadType === me.UPLOADTYPE.XHR
        },
        checkSendGetBeforeUpload: function () {
            var e = this;
            if (Airdroid.Util.isHttps() && !Airdroid.DeviceManage.isCurrentDeviceRemote() && e.checkUploadToPhone() && Airdroid.Util.browser.chrome) {
                var t = window.navigator.userAgent.indexOf("Chrome/");
                if (34 > parseInt(window.navigator.userAgent.substr(t + 7, 2))) return !0
            }
            return !1
        },
        refreshDirUploadStates: _.throttle(function (e) {
                var me = this;
                Airdroid.DeviceManage.getDirUploadStates(
                    me._uploadFilePath,
                    function (i) {
                        console.log(" " + i),
                            me._avail = i.avail,
                            me._allowSupport = "1" == i.support ? !0 : !1,
                            _.isFunction(e) && e(i)
                    })
            },
            2e3),
        checkAvaiData: function (e) {
            var t = this;
            return t.checkUploadToPhone() && t._avail ? t._avail > e.size ? (t._avail = t._avail - e.size, !0) : (Airdroid.Util.alert(t._uploadLang.Msg_not_avail), !1) : !0
        },
        checkUploadToPhone: function () {
            var e = this;
            return e._uploadServer === e.UPLOADSERVERTYPE.PHONE
        },
        checkMonthDataFlowWhileRemote: function (e) {
            var t = this;
            if (Airdroid.DeviceManage.isCurrentDeviceRemote() && t.checkUploadToPhone()) {
                if (Airdroid.UserManage.checkMonthDataFlowOverage()) return console.info("month data over flow!!!"),
                    !0;
                if (e.size > 1024 * 1024 * Airdroid.Config.uploadMaxPerFileSize) {
                    if (Airdroid.Util.checkPremium() && e.size > 1024 * 1024 * Airdroid.Config.uploadMaxPerFileSizePremium) return Airdroid.Util.alert(t._uploadLang.RemoteMode_FileTooLarge.format(Airdroid.Config.uploadMaxPerFileSizePremium)),
                        !0;
                    if (!Airdroid.Util.checkPremium()) return Airdroid.Util.confirm(t._commonLang.RemoteMode_FileTooLarge_F.format(Airdroid.Config.uploadMaxPerFileSize, Airdroid.Config.uploadMaxPerFileSizePremium),
                        function () {
                            Airdroid.Util.showPremiumTip(Airdroid.Util._goPremiumType.remote_free_upload_more_10)
                        }),
                        !0
                } else if (Airdroid.Util.checkDataOverage(e.size)) return Airdroid.Util.checkPremium() ? (Airdroid.Util.alert(t._uploadLang.DataFlowNotAbleToUpload,
                    function () {
                        t.isXHR() && t.upload()
                    }), !0) : (Airdroid.Util.confirm(t._uploadLang.DataFlowNotAbleToUpload_P,
                    function () {
                        Airdroid.Util.showPremiumTip(Airdroid.Util._goPremiumType.remote_free_upload_overage),
                            t.isXHR() && t.upload()
                    }), !0)
            }
            return !1
        },
        checkSupportUpload: function () {
            var e = this;
            return e._allowSupport ? !0 : (Airdroid.Util.alert(e._commonLang.upload_Permission_Denied), !1)
        },
        checkAllowUpload: function (e) {
            var me = this;
            return !me.checkMonthDataFlowWhileRemote(e) && me.checkAvaiData(e) && me.checkSupportUpload()
        },
        setGA: function (e) {
            var t = this;
            Airdroid.Util.trackEvent("M-Upload", "Extension", e.name.substr(e.name.lastIndexOf(".") + 1).toLowerCase()),
                    1048576 > e.size ? Airdroid.Util.trackEvent("M-Upload", "Size", "Lt1m") : Airdroid.Util.trackEvent("M-Upload", "Size", t.getGaFileSize(e.size))
        },
        getGaFileSize: function (e) {
            // e = Math.floor(e / 1048576);
            e = e >> 20;    //(MB)
            var t = ("" + e).length,
                i = Math.pow(10, t - 1);
            return e = Math.floor(e / i) * i,
                    e >= 1e3 ? "" + e / 1e3 + "G" : "" + e + "M"
        },
        getErrorMsgByCode: function (e) {
            var t = this;
            e = !_.isUndefined(e) && parseInt(e);
            var i = t._commonLang.upload_network_error;
            switch (e) {
                case 0:
                    i = t._commonLang.fail_to_upload;
                    break;
                case -1 :
                    i = t._commonLang.apk_decode_error;
                    break;
                case -2 :
                    i = t._uploadLang.Msg_not_avail;
                    break;
                case -3 :
                    i = t._commonLang.upload_Permission_Denied
            }
            return i
        },
        init: function (config) {
            var uploader = null;
            if (Airdroid.Util.isSupportXHR()) {
                var setttings = {
                        url: Airdroid.Service.getFileUploadPath(),
                        params: {
                            fn: config.common.fname || "",
                            d: config.common.fpath || "",
                            after: config.common.afterAction || "0"
                        },
                        maxfiles: 3,
                        maxfilesize: -1,
                        uploadStarted: function (id, n) {
                            console.log("start upload==" + n.name + ",url=" + this.url),
                                uploader.checkUploadToPhone() && (this.url = Airdroid.Service.getFileUploadPath()),
                                n.id = id,
                                $.isFunction(config.common.uploadStarted) && (config.common.uploadStarted(n, uploader._uploadType), uploader.setGA(n))
                        },
                        progressUpdated: function (id, n, o) {
                            n.id = id, $.isFunction(config.common.progressUpdated) && config.common.progressUpdated(n, o, uploader._uploadType)
                        },
                        uploadFinished: function (i, n, o) {
                            n.id = i;
                            var r = _.isObject(o) ? o : $.parseJSON(o);
                            1 == r.result ? $.isFunction(config.common.uploadFinished) && config.common.uploadFinished(n, r.data, uploader._uploadType) : uploader.uploadError(r.result, n)
                        },
                        error: function (i, n) {
                            n = n || {},
                                n.id = n.index || "",
                                i = i || uploader._commonLang.fail_to_upload,
                                $.isFunction(config.common.error) && config.common.error(n, i, uploader._uploadType),
                                uploader.refreshDirUploadStates()
                        },
                        cancel: function (t) {
                            $.isFunction(config.common.cancel) && config.common.cancel(t)
                        }
                    },
                    config = $.extend(!0, {}, setttings, config.xhr);
                config.supportFolderUpload && (Airdroid.Util.browser.chrome || (config.folderUploadBtnParentElement = null)),
                    uploader = new Airdroid.XhrUploader,
                    uploader.init(config)
            } else {
                if (this._uploadType = this.UPLOADTYPE.FLASH, !config.flash) return {};
                $.isFunction(config.flash.beforeInit) && (config.flash.beforeInit(), delete config.flash.beforeInit);
                var settings = {
                        flash_url: Airdroid.Config.baseUri + "assets/swf/swfupload.swf",
                        flash9_url: Airdroid.Config.baseUri + "assets/swf/swfupload_fp9.swf",
                        upload_url: Airdroid.Service.getFlashUploadPath(),
                        use_query_string: !0,
                        file_types: "*.*",
                        file_types_description: Airdroid.Util.getLang("Upload", "Label_FileTypesDesc"),
                        button_placeholder_id: "",
                        button_image_url: Airdroid.Service.getImgAssets("feature/select_files.png"),
                        button_width: config.flash.buttonWidth,
                        button_height: config.flash.buttonHeight,
                        button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES,
                        button_cursor: SWFUpload.CURSOR.HAND,
                        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                        file_dialog_start_handler: function () {
                            uploader.checkUploadToPhone() && this.setUploadURL(Airdroid.Service.getFlashUploadPath()),
                                console.log("dialog_start")
                        },
                        file_dialog_complete_handler: function () {
                            console.log("dialog_start upload"),
                                this.startUpload()
                        },
                        file_queued_handler: function (i) {
                            $.isFunction(config.common.uploadStarted) && (config.common.uploadStarted(i, uploader._uploadType), uploader.setGA(i)),
                                console.log("file_queued_handler")
                        },
                        upload_start_handler: function (i) {
                            if (uploader.checkAllowUpload(i)) {
                                var n = {
                                        loader: "2",
                                        fname: i.name,
                                        fpath: config.common.fpath,
                                        after: config.common.afterAction || "0",
                                        rtype: config.common.rtype || "0"
                                    },
                                    o = $.extend(!0, n, config.flash.param);
                                this.setPostParams(o)
                            } else this.cancelUpload(i.id, !0)
                        },
                        upload_progress_handler: function (i, n, o) {
                            var r = Math.round(100 * (n / o));
                            $.isFunction(config.common.progressUpdated) && config.common.progressUpdated(i, r, uploader._uploadType)
                        },
                        upload_error_handler: function (i, n, o) {
                            console.log("flash upload error==>" + o),
                                $.isFunction(config.common.error) && config.common.error(i, uploader._commonLang.fail_to_upload, uploader._uploadType),
                                uploader.refreshDirUploadStates()
                        },
                        upload_success_handler: function (i, n) {
                            var o = $.parseJSON(n);
                            1 == o.result ? $.isFunction(config.common.uploadFinished) && config.common.uploadFinished(i, o.data, uploader._uploadType) : $.isFunction(config.common.error) && config.common.error(i, uploader.getErrorMsgByCode(o.result), uploader._uploadType)
                        }
                    },
                    o = $.extend(!0, {}, settings, config.flash);
                uploader = new SWFUpload(o)
            }
            this._uploadFilePath = config.common.fpath || this._defaultFpath;
            var me = this;
            for (var m in me) uploader[m] = $.isFunction(me[m]) && "init" != m ? me[m] : me[m];
            return uploader.refreshDirUploadStates(), uploader
        }
    },

    //

    Airdroid.XhrUploader = Core.extend({
        maxListItemsOneTime: 30,
        listItemTimeInterval: 1500,
        listUploadItemsTimer: null,
        isCancel: !1,
        $construct: function () {
            console.info("XhrUploader========"),
                this.opts = {},
                this.default_opts = {
                    fileUploadBtnParentElement: null,
                    folderUploadBtnParentElement: null,
                    dropArea: null,
                    url: "",
                    params: {},
                    maxfiles: 10,
                    maxfilesize: 1,
                    isMultiple: !0,
                    data: {},
                    isFitDir: !0,
                    drop: function () {
                    },
                    dragEnter: function () {
                    },
                    dragOver: function () {
                    },
                    dragLeave: function () {
                    },
                    beforeEach: function () {
                    },
                    afterAll: function () {
                    },
                    rename: function () {
                    },
                    error: function (e) {
                        alert(e)
                    },
                    cancel: function () {
                    },
                    uploadStarted: function () {
                    },
                    uploadFinished: function () {
                    },
                    progressUpdated: function () {
                    },
                    beforeLoad: function () {
                    },
                    afterLoad: function () {
                    }
                },
                this.errors = ["BrowserNotSupported.", "TooManyFiles.", "FileTooLarge.", "Error."],
                this.files = [],
                this.fileSelectBtn = null,
                this.folderSelectBtn = null,
                this.uploadXHRs = []
        },
        init: function (e) {
            var me = this;
            me.uploadXHRs = [],
                me.files = [],
                me.fileSelectBtn = null,
                me.folderSelectBtn = null,
                jQuery.event.props.push("dataTransfer"),
                console.info(e),
                me.opts = $.extend(me.default_opts, e);
            var i = Airdroid.Util.getLang("Upload", "Button_SelectFiles");
            me.opts.selectFilesBtnTitle && (i = me.opts.selectFilesBtnTitle),
                null != me.opts.fileUploadBtnParentElement && (me.fileSelectBtn = Airdroid.Util.browser.safari || !me.opts.isMultiple ? $('<form><input type="file"  name="file" style=" width:100%;height:100%;"/></form>') : $('<form><input multiple="multiple" type="file"  name="file" style=" width:100%;height:100%;"/></form>'), me.opts.fileUploadBtnParentElement.append(me.fileSelectBtn), me.opts.fileUploadBtnParentElement.css({
                position: "relative",
                cursor: "pointer"
            }), me.fileSelectBtn.css({
                position: "absolute",
                right: "0px",
                top: "0px",
                width: "100%",
                height: "100%",
                margin: "0pt",
                padding: "0pt",
                cursor: "pointer",
                opacity: 0
            }), me.fileSelectBtn.find("input").change(function (e) {
                var i = e.target.files,
                    n = i.length,
                    o = function () {
                        me.onFileInputChange(i,
                            function () {
                                $(e.currentTarget).parents("form")[0].reset()
                            })
                    };
                n > 250 ? Airdroid.Util.confirm(Airdroid.Util.getLang("Filemanage", "Message_FileItemMore"), o,
                    function () {
                        $(e.currentTarget).parents("form")[0].reset()
                    }) : o()
            }).attr("title", i)),
                null != me.opts.folderUploadBtnParentElement && (me.folderSelectBtn = $('<form><input multiple="multiple" type="file" name="file[]" webkitdirectory="" directory="" mozdirectory style=" width:100%;height:100%;"/></form>'), me.opts.folderUploadBtnParentElement.append(me.folderSelectBtn), me.opts.folderUploadBtnParentElement.css({
                position: "relative",
                cursor: "pointer"
            }), me.folderSelectBtn.css({
                position: "absolute",
                right: "0px",
                top: "0px",
                width: "100%",
                height: "100%",
                margin: "0pt",
                padding: "0pt",
                cursor: "pointer",
                opacity: 0
            }), me.folderSelectBtn.find("input").change(function (e) {
                var i = e.target.files,
                    n = i.length;
                if (!(1 > n)) {
                    var o = function () {
                            $(e.currentTarget).parent("form")[0].reset()
                        },
                        r = function () {
                            if (me.opts.isFitDir && "" != i[0].webkitRelativePath) {
                                me.beforeLoad();
                                var n = {
                                    objname: i[0].webkitRelativePath.split("/")[0],
                                    d: me.opts.params.d,
                                    isfile: 0
                                };
                                Airdroid.Service.checkNameExit(n,
                                    function (n) {
                                        me.afterLoad(),
                                                n.oldname == n.newname ? me.onFileInputChange(i, o) : Airdroid.Util.confirm(Airdroid.Util.getLang("Upload", "NameExistSureRename").format(n.oldname, n.newname),
                                            function () {
                                                me.beforeLoad();
                                                var r = [];
                                                _.each(i,
                                                    function (e) {
                                                        r.push(e)
                                                    });
                                                var a = function () {
                                                    for (var e = [], i = 0; me.maxListItemsOneTime > i; i++) r.length > 0 && e.push(r.shift());
                                                    return e
                                                };
                                                if (me.startUploadFolderQueque(a(), n.oldname, n.newname, e), r.length > 0) var s = setInterval(function () {
                                                        var i = a();
                                                        i.length > 0 ? me.startUploadFolderQueque(i, n.oldname, n.newname, e) : (o(), clearInterval(s))
                                                    },
                                                    me.listItemTimeInterval);
                                                else o();
                                                me.afterLoad()
                                            },
                                            function () {
                                                o()
                                            })
                                    },
                                    function () {
                                        me.afterLoad(),
                                            me.onFileInputChange(i, o)
                                    })
                            } else me.onFileInputChange(i, o)
                        };
                    n > 250 ? Airdroid.Util.confirm(Airdroid.Util.getLang("Filemanage", "Message_FileItemMore"), r,
                        function () {
                            o()
                        }) : r()
                }
            }).attr("title", Airdroid.Util.getLang("Upload", "Button_SelectFolder"))),
                _.bindAll(me, "progress", "rename", "upload", "onFileInputChange"),
                _.bindAll(me, "drop", "dragEnter", "dragOver", "dragLeave", "drop"),
                me.setDropArea(me.opts.dropArea)
        },
        onFileInputChange: function (e, t) {
            var i = this;
            i.beforeLoad();
            var n = [];
            _.each(e,
                function (e) {
                    n.push(e)
                });
            var o = function () {
                for (var e = [], t = 0; i.maxListItemsOneTime > t && n.length > 0; t++) e.push(n.shift());
                return e
            };
            return i.startUploadQueque(o()),
                    n.length > 0 ? i.listUploadItemsTimer = setInterval(function () {
                    var e = o();
                    e.length > 0 ? i.startUploadQueque(e) : (t(), clearInterval(i.listUploadItemsTimer))
                },
                i.listItemTimeInterval) : t(),
                i.afterLoad(),
                !1
        },
        startUploadQueque: function (e) {
            var t = this;
            return _.each(e,
                function (e) {
                    if (t.beforeEach(e) !== !1) {
                        var i = t.getUniqueId("uploadfileitem");
                        e.index = i,
                            "." != e.name && (e.fullpath = t.opts.params.d + "/" + t.getFilePath(e), t.opts.uploadStarted(i, e), t.files.push(e))
                    }
                }),
                    null === t.files || void 0 === t.files ? !1 : (t.upload(), void 0)
        },
        startUploadFolderQueque: function (e, t, i, n) {
            var o = this;
            return _.each(e,
                function (e) {
                    if (o.beforeEach(e) === !1) return $(n.currentTarget).parents("form")[0].reset(),
                        !1;
                    var r = o.getUniqueId("uploadfileitem");
                    e.index = r,
                        e._webkitRelativePath = e.webkitRelativePath.replace(t + "/", i + "/"),
                        "." != e.name && (e.fullpath = o.opts.params.d + "/" + e._webkitRelativePath, o.opts.uploadStarted(r, e), o.files.push(e))
                }),
                    null === o.files || void 0 === o.files ? !1 : (o.upload(), void 0)
        },
        drop: function (e) {
            this.opts.drop(e);
            var me = this;
            if (e.dataTransfer) {
                if (e.dataTransfer.items && _.isFunction(e.dataTransfer.items[0].webkitGetAsEntry)) {
                    console.log("support folder");
                    for (var i = e.dataTransfer.items,
                             n = 0; i.length > n; n++) {
                        var entry = i[n].webkitGetAsEntry();
                        entry && me.traverseFileTree(entry, "", e.currentTarget)
                    }
                } else {
                    console.log("not support folder");
                    if (_.each(e.dataTransfer.files, function (file) {
                            me.beforeLoad(),
                                me.isFolder(file,
                                    function (n) {
                                        if (n) me.opts.error(Airdroid.Util.getLang("Upload", "notsupportdragfolders"));
                                        else if (file.dropArea = e.currentTarget, 0 != me.beforeEach(file)) {
                                            var id = me.getUniqueId("uploadfileitem");
                                            file.index = id,
                                                file.fullpath = me.opts.params.d + "/" + me.getFilePath(file),
                                                me.opts.uploadStarted(id, file),
                                                me.files.push(file)
                                        }
                                    })
                        }), null === me.files || void 0 === me.files) return me.opts.error(me.errors[0]),
                        !1;
                    me.afterLoad(),
                        me.upload()
                }
                return e.preventDefault(),
                    !1
            }
        },
        isFolder: function (file, callback) {
            var i;
            if (callback = callback || $.noop, !file.type && 0 == file.size % 4096 && 102400 >= file.size) {
                try {
                    i = new FileReader,
                        i.onerror = function () {
                            callback(true)
                        },
                        i.onload = function () {
                            callback(false)
                        },
                        i.readAsDataURL(file)
                } catch (n) {
                    callback(true)
                }
            } else {
                callback(false)
            }
        },
        traverseFileTree: function (e, path, i) {
            var n = this;
            path = path || "";
            if (e.isFile) e.file(function (file) {
                if (console.log("File:", path + file.name), file.dropArea = i, 0 != n.beforeEach(file)) {
                    var o = n.getUniqueId("uploadfileitem");
                    if (file.index = o, "" != Airdroid.Util.getFileExt(file.name)) {
                        if (file.fullpath = n.opts.params.d + "/" + path + n.getFilePath(file), file.parentPath = path, n.opts.uploadStarted(o, file), n.files.push(file), null === n.files || void 0 === n.files) return n.opts.error(n.errors[0]),
                            !1;
                        n.files && 1 == n.files.length && (n.afterLoad(), n.upload())
                    }
                }
            });
            else if (e.isDirectory) {
                var o = {
                    objname: path + e.name,
                    d: n.opts.params.d,
                    isfile: 0
                };
                Airdroid.Service.checkNameExits(o,
                    function (o) {
                        if (n.afterLoad(), o.oldname == o.newname) {
                            var r = e.createReader();
                            r.readEntries(function (o) {
                                for (var r = 0; o.length > r; r++) n.traverseFileTree(o[r], path + e.name + "/", i)
                            })
                        } else {
                            (function (e) {
                                Airdroid.Util.addBlockSingle(function () {
                                    Airdroid.Util.confirm(Airdroid.Util.getLang("Upload", "NameExistSureRename").format(o.oldname, o.newname),
                                        function () {
                                            var r = e.createReader();
                                            r.readEntries(function (e) {
                                                for (var r = 0; e.length > r; r++) {
                                                    var a = o.newname;
                                                    n.traverseFileTree(e[r], path + a + "/", i)
                                                }
                                            })
                                        })
                                })
                            })(e);
                        }
                    })
            }
        },
        cancelUpload: function (e, t) {
            var i = this,
                n = function () {
                    _.each(i.uploadXHRs,
                        function (t) {
                            t.upload.file.index == e && (t.abort(), i.clearResendTimeId(t), i.uploadXHRs = _.without(i.uploadXHRs, t), i.opts.cancel && i.opts.cancel(t.upload.file))
                        })
                };
            if (0 == t) {
                var o = !1;
                _.each(i.files,
                    function (t) {
                        t.index == e && (o = !0, i.files = _.without(i.files, t), i.opts.cancel && i.opts.cancel(t))
                    }),
                    o || n()
            } else n();
            i.upload()
        },
        cancelAll: function (e, t) {
            var i = this;
            $.isFunction(e) && e(),
                _.each(i.uploadXHRs,
                    function (e) {
                        e.abort(),
                            i.clearResendTimeId(e),
                            i.uploadXHRs = _.without(i.uploadXHRs, e)
                    }),
                i.files = [],
                t || (i.isCancel = !0),
                clearInterval(i.listUploadItemsTimer)
        },
        progress: function (e) {    // 进度处理
            var me = this, upload = e.target;
            if (e.lengthComputable && me.opts) {
                var n = Math.round(100 * e.loaded / e.total);
                if (upload.currentProgress != n) {
                    upload.currentProgress = n;
                    var speed = "0Kb/s";
                    me.opts.progressUpdated(upload.file.index, upload.file, upload.currentProgress, speed);
                }
            }
        },
        clearResendTimeId: function (e) {
            e.reSendTimeId && clearTimeout(e.reSendTimeId)
        },
        uploadFile: function (file) {
            var me = this,
                xhr = new XMLHttpRequest,
                startTime = (new Date).getTime();
            // 附加属性
            xhr.reSendTimeId = null;
            xhr.upload.file = file;
            xhr.upload.currentStart = startTime;
            xhr.upload.currentProgress = 0;
            xhr.upload.startData = 0;

            // upload complete
            xhr.onload = function (e) { // <==> addListener("load", func, false)
                console.info(e.currentTarget + "=====》");
                me.clearResendTimeId(xhr);
                var xhr = e.currentTarget;
                if (xhr.responseText) if ('{"err": "forbidden"}' == xhr.responseText) Airdroid.CenterManage.onServerForbidden();
                else {
                    me.uploadXHRs = _.without(me.uploadXHRs, xhr);
                    var endTime = (new Date).getTime(), a = endTime - startTime;
                    "." != xhr.upload.file.name && me.opts.uploadFinished(xhr.upload.file.index, xhr.upload.file, xhr.responseText, a);
                    0 == me.files.length && 0 == me.uploadXHRs.length && me.afterAll();
                    me.upload();
                }
            };
            // upload failed
            xhr.onerror = function () {
                me.clearResendTimeId(xhr);
                me.uploadError(null, file);
            };
            me.opts.params && (me.opts.params.fn = me.getFilePath(file), me.opts.params.fname = me.getFilePath(file), me.opts.params.needSize && (me.opts.params.fsize = file.size, delete me.opts.params.needSize));

            var uploadUrl = me.opts.url;
            Airdroid.Util.browser.ie10 || Airdroid.Util.browser.ie11 ? (me.opts.params = me.opts.params || {},
                me.opts.params.account_sid = Airdroid.Util.getCookie("account_sid") || "") : xhr.withCredentials = !0,
                uploadUrl = /\?/.test(me.opts.url) ? me.opts.url + "&" + $.param(me.opts.params) : me.opts.url + "?" + $.param(me.opts.params),

                console.info("uploadUrl ===> " + uploadUrl),
                xhr.open("POST", uploadUrl, true),
                xhr.setRequestHeader("Content-Type", "application/octet-stream"),
                "." != file.name && xhr.upload.addEventListener("progress", me.progress, false),
                xhr.send(file),

                me.checkSendGetBeforeUpload() && (xhr.reSendTimeId = setTimeout(function () {
                    0 == xhr.upload.currentProgress && (console.debug(""), me.uploadXHRs = _.without(me.uploadXHRs, xhr), xhr.abort(), Airdroid.Util.getHttpsUpload(function () {
                        me.uploadFile(file)
                    }))
                },
                15e3)),
                me.uploadXHRs.push(xhr)
        },
        upload: function () {
            var me = this;
            if (!me.files) return me.opts.error(me.errors[0]), !1;
            var t = function () {
                if (!Airdroid.DeviceManage.isCurrentDeviceConnected()) return me.cancelAll(function () {
                        for (; me.files.length > 0;) {
                            var t = me.files.shift();
                            me.opts.error(me._commonLang.upload_network_error, t)
                        }
                        _.each(me.uploadXHRs,
                            function (t) {
                                t.upload.file && (t.abort(), me.clearResendTimeId(t), me.uploadXHRs = _.without(me.uploadXHRs, t), me.opts.error(me._commonLang.upload_network_error, t.upload.file))
                            })
                    },
                    !0),
                    !1;
                for (; me.uploadXHRs.length < me.opts.maxfiles && me.files.length > 0 && !me.isCancel;) {
                    var file = me.files.shift();
                    try {
                        if (!me.checkAllowUpload(file)) {
                            me.uploadError(null, file);
                            continue
                        }
                        me.uploadFile(file)
                    } catch (i) {
                        return me.opts.error(me.errors[3]),
                            !1
                    }
                }
            };
            me.checkSendGetBeforeUpload() ? Airdroid.Util.getHttpsUpload(function () {
                t()
            }) : t()
        },
        getUniqueId: function (e) {
            return _.uniqueId(e)
        },
        getFilePath: function (file) {
            var t = file.name;
            return this.opts.isFitDir && (t = file.webkitRelativePath, file._webkitRelativePath && (t = file._webkitRelativePath), ("" == t || _.isUndefined(t)) && (t = file.name)),
                file.parentPath && (t = file.parentPath + t),
                t
        },
        rename: function (e) {
            return this.opts.rename(e)
        },
        beforeEach: function (e) {
            return "." == e.name ? !0 : this.opts.beforeEach(e)
        },
        afterAll: function () {
            return this.opts.afterAll()
        },
        dragEnter: function (e) {
            e.preventDefault(),
                this.opts.dragEnter(e)
        },
        uploadError: function (e, t) {
            var i = this;
            i.opts.error(i.getErrorMsgByCode(e), t),
                Airdroid.DeviceManage.isCurrentDeviceConnected() && _.each(i.uploadXHRs,
                function (e) {
                    e.upload.file.index == t.index && (e.abort(), i.clearResendTimeId(e), i.uploadXHRs = _.without(i.uploadXHRs, e), i.upload())
                })
        },
        dragOver: function (e) {
            e.preventDefault(),
                this.opts.dragOver(e)
        },
        dragLeave: function (e) {
            this.opts.dragLeave(e),
                e.stopPropagation()
        },
        beforeLoad: function () {
            this.opts.beforeLoad()
        },
        afterLoad: function () {
            this.opts.afterLoad()
        },
        setFilePath: function (e) {
            this.opts.params.d = e,
                this._uploadFilePath = e,
                this.refreshDirUploadStates()
        },
        setDropArea: function (e) {
            this.unbindDropArea(this.opts.dropArea),
                this.opts.dropArea = this.removeRedundancyDropArea(e),
                this.bindDropArea(this.opts.dropArea)
        },
        addDropArea: function (e) {
            this.opts.dropArea = this.opts.dropArea.add(e),
                this.setDropArea(this.opts.dropArea)
        },
        isDropArea: function (e) {
            return this.opts.dropArea.find(e).length > 0
        },
        removeDropArea: function (e) {
            this.unbindDropArea(e),
                this.opts.dropArea = this.opts.dropArea.not(e)
        },
        removeRedundancyDropArea: function (e) {
            return $("body").find(e)
        },
        getDropArea: function () {
            return this.opts.dropArea
        },
        unbindDropArea: function (e) {
            e && (_.isArray(e) ? _.each(this.opts.dropArea,
                function (e) {
                    e.unbind("drop").unbind("dragenter").unbind("dragover").unbind("dragleave")
                }) : e.unbind("drop dragenter dragover dragleave"))
        },
        bindDropArea: function (e) {
            if (e) {
                var me = this;
                _.isArray(e) ? _.each(e,
                    function (e) {
                        e.bind("drop", me.drop).bind("dragenter", me.dragEnter).bind("dragover", me.dragOver).bind("dragleave", me.dragLeave)
                    }) : e.bind("drop", me.drop).bind("dragenter", me.dragEnter).bind("dragover", me.dragOver).bind("dragleave", me.dragLeave)
            }
        }
    });